


import sys
import requests,time,json


from function.tools import *

# logger = log.log(__name__)

iovConf = conf.loadConfIni('iovConf')
class TspApi():
    #主页地址
    token = ''

    # HOST = "https://testiov.molichuxing.com"
    HOST = 'https://iov.molichuxing.com'
    
    #接口主地址
    api_info = iovConf.api_info
    # logger.info(api_info)
    # APIHOST = "https://testiovif.molichuxing.com"
    APIHOST = iovConf.get(api_info)
    if api_info == 'api_host':
        for i in range(3):
            flag = get_input('当前接口地址为生产环境,是否继续运行脚本')
            if flag.lower() == 'y':
                break
            elif flag.lower() == 'n':
                sys.exit()
    url = f"{HOST}/tbox/home/login"
    header = {"Content-Type":"application/json;charset=UTF-8",
            "User-Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36",
            "Referer":f"{HOST}/tbox"
            }
    data = {
        "account":iovConf.user,
        "password":'mlkj'+strToBase64(iovConf.passwd)
        }
    # logger.info(data)
    # time.sleep(10000)

    def __init__(self):
        self.HOST = "https://testiov.molichuxing.com"
        #接口主地址
        self.APIHOST = "https://testiovif.molichuxing.com"
        self.url = f"{self.HOST}/tbox/home/login"
        self.header = {"Content-Type":"application/json;charset=UTF-8",
                "User-Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36",
                "Referer":f"{self.HOST}/tbox"
                }
        self.data = {
            "account":iovConf.user,
            "password":'mlkj'+strToBase64(iovConf.passwd)
            }
            # self.login()
    def connectHttp(self,methon, url, **krawgs):
        logger.debug(f'http请求:{krawgs}')
        self.res = requests.request(methon, url, **krawgs)
        contenText = self.res.content
        logger.debug(f'http返回:{contenText}')
        self.resJson = json.loads(contenText.decode())
        
        logger.debug(self.resJson)
        return d2o(self.resJson)
    def login(self):
        # logger.info('当前token为:'+self.token)
        if self.token:
            return self.token
        else:
            self.resJson = self.connectHttp('post',f'{self.APIHOST}/auth/user/login',
                            data= json.dumps(self.data),
                            headers= self.header)
            # logger.info(self.resJson)
            if self.resJson.flag == True:
                self.token = self.resJson.data.token
                self.header['token'] = self.token
                logger.debug('当前token为:'+self.token)
            else:
                logger.error(self.resJson.message)
                sys.exit()
    def getAttr(self,key):
        self.__init__()
        return getattr(self,key)
class Vehicle(TspApi):
    def __init__(self,vin):
        self.vin = vin
    def getVehicleList(self):
        '''带vin参数搜索车辆列表'''
        url = f'{self.APIHOST}/monitor/vehicleManagement/list'
        # self.header['Referer'] = 'https://testiov.molichuxing.com/tbox/monitor/position/info'
        data = {"vin":self.vin,"pageNum":1,"pageSize":10}
        self.resJson = self.connectHttp('POST', url, headers = self.header, data = json.dumps(data))
        # self.resJson = json.loads(self.resJson.content.decode())
        logger.info(self.resJson)
        return self.resJson
    def getVehicleId(self,index= 0):
        '''从车辆列表中获取车辆id
        需要先执行getVehicleList
        '''
        # self.getVehicleList()
        logger.info(self.resJson['data']['records'])
        
        self.vehicleId = self.resJson['data']['records'][index]['id']
        # self.vehicleId = self.VehicleListRes['data']
        # self.vehicleId = self.resJson
        return self.vehicleId
    def vehicleUpdate(self):
        '''更新车辆列表车辆信息'''
        url = f'{self.APIHOST}/monitor/vehicleManagement/vehicle/update'
        data = {
            "brand": "238",
            "companyId": 1,
            "vehicleSeries": "4850",
            "license": f"京AD3{self.vin[-5::]}",
            "vehicleType": "44718",
            "vin": self.vin,
             "id":self.vehicleId}
        res = requests.post(url,
                headers = self.header,
                data = json.dumps(data)
        )
        logger.info(res.content.decode())
        return res
    def vehicleDetails(self):
        '''获取车辆详情'''
        PARAMS = {"vin":self.vin}
        # url = f'{self.APIHOST}/monitor/vehicleDetails/data'
        url = f'{self.APIHOST}/monitor/vehicleManagement/details'
        
        self.resJson = requests.post(url,
        data= json.dumps(PARAMS),
        headers= self.header)
        self.vehicle_json = self.resJson.json()
        self.mileage = self.getJsonDataValue('odometer')
        self.devices_id = self.getJsonDataValue('deviceId')
        self.iccId = self.getJsonDataValue('iccid')
        self.longitude = self.getJsonDataValue('longitude')
        self.latitude = self.getJsonDataValue('latitude')
        self.GpsMileage = self.getJsonDataValue('extendGpsOde')
    
        # logger.info(self.iccId,'=======================================')
        # logger.info('sdfsdfsdfsdfsdsfsdfsd')
        # logger.info(self.vehicle_json)
    
    def requestsBool(self,response):
        flag = False if response.get('message') != "成功" else True
        return flag
    def get_mileage(self,vin=''):
        #logger.info(self.requestsBool(self.vehicle_json))
        # self.vehicleDetails()
        if not self.requestsBool(self.vehicle_json):
            return '里程查询失败'
        # if  self.vehicle_json.get('data'):
            # LNBSCB3F0JW176205logger.info(self.vehicle_json['data'])
            # self.mileage = self.vehicle_json['data']["odometer"]
            # self.divicesId = self.vehicle_json['data']["odometer"]
            # self.mileage = self.getJsonDataValue('odometer')
            # return self.mileage
        # else:
# cmd /k python.exe "$(FULL_CURRENT_PATH)" &PAUSE &EXIT

            # logger.info('当前车辆不存在')
        self.mileage = self.getJsonDataValue('odometer')
        self.devices_id = self.getJsonDataValue('deviceId')
        return self.mileage if self.mileage else 0
    def getJsonDataValue(self,key:str) ->str:
        if  self.vehicle_json.get('data').get('vin'):
            # logger.info(self.vehicle_json)
            self.value = self.vehicle_json['data'][key]
            return self.value
        else:
        
            raise Exception(f'{self.vin}当前车辆不存在,继续输入则创建车辆')
class Alarm(Vehicle):

    def __init__(self, vin=''):
        self.vin = vin 
        self.login() if vin else 1
    def relieveAlarm(self):
            
        url = f'{self.APIHOST}/alarm/alarmEquipmentRecord/update'
        data = {"alarmId":self.alarmId}
        self.resJson = requests.post(url, headers = self.header, data = json.dumps(data) )
        self.resJson = self.resJson.content.decode()
        # logger.info(self.resJson)
        return self.resJson
    # def getAlarmList(self, vin, alarmType=1)->str:
    def getAlarmList(self,  alarmType=1)->str:
        url = f'{self.APIHOST}/alarm/alarmEquipmentRecord/list'
        self.data = {"queryParam":alarmType,"queryValue":self.vin,"pageNum":1,"pageSize":10}
        self.resJson = requests.post(url,
                                    data = json.dumps(self.data),
                                    headers = self.header
                                ).content.decode()
        logger.info(self.resJson)
        return self.resJson
        
    def getAlarmId(self)->str:

        self.alarmId = json.loads(self.resJson)['data']['records'][0]['alarmId']
        logger.info(self.alarmId+'报警id')
        return self.alarmId

if __name__ == "__main__":
    # vehicleDetails = VehicleDetails('MOLICB3F9JW100161')
    # logger.info(vehicleDetails.getJsonDataValue('odometer'))
    
    alarm = Alarm('MOLICB3F9JW100161')
    
    alarm.login()
    token1 = alarm.token
    alarm.getVehicleList()
    alarm = Alarm('MOLICB3F9JW100161')
    alarm.login()
    token2 = alarm.token
    # logger.info()
    logger.info(alarm.token+'\n'+token2)
    logger.info(token1==token2)
    # logger.info(alarm.getVehicleId())
    # alarm.vehicleUpdate()
    # alarm.vehicleDetails()
    # logger.info(alarm.devices_id)
    # # logger.info(alarm.vehicleUpdate())
    # # alarm.getAlarmList()
    # # alarm.getAlarmId()
    # # logger.info(alarm.getAlarmId())
    # # alarm.relieveAlarm()


    
    
    
    
    
    
    
    
    
    
    